/*
 * Powered By fanrenqij.com
 * Since 2017 - 2017
 */

package com.fanrenqiji.modules.business.event.service.impl;

import com.aliyun.oss.common.utils.DateUtil;
import com.fanrenqiji.common.mapper.BeanMapper;
import com.fanrenqiji.common.utils.DateUtils;
import com.fanrenqiji.entity.*;
import com.fanrenqiji.modules.business.event.dao.EventDetailDao;
import com.fanrenqiji.modules.business.eventcase.dao.EventCaseDao;
import com.fanrenqiji.modules.business.eventcase.vo.EventCaseVO;
import com.fanrenqiji.modules.business.parentdailyscore.dao.ParentDailyScoreDao;
import com.fanrenqiji.modules.business.semester.dao.SemesterDao;
import com.fanrenqiji.modules.business.wechatuser.dao.WeChatUserDao;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;

import com.fanrenqiji.modules.business.event.vo.EventVO;
import com.fanrenqiji.modules.business.event.dao.EventDao;
import com.fanrenqiji.modules.business.event.service.EventService;

import org.dozer.DozerBeanMapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.fanrenqiji.common.persistence.Page;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Order;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.Timestamp;

/**
 * 课程事件表业务逻辑实现
 *
 * @author wentao
 */
@Service(value = "event")
@Transactional(readOnly = true)
public class EventServiceImpl implements EventService {

    @Autowired
    private EventDao eventDao;

    @Autowired
    private EventDetailDao eventDetailDao;

    @Autowired
    DozerBeanMapper beanMapper;

    @Autowired
    WxMpService wxService;

    @Autowired
    SemesterDao semesterDao;

    @Autowired
    WeChatUserDao weChatUserDao;
    @Autowired
    EventCaseDao eventCaseDao;
    @Autowired
    ParentDailyScoreDao parentDailyScoreDao;

    /**
     * 插入
     *
     * @param event 插入的对象
     * @return 插入数据条数
     */
    @Transactional
    public EventVO insert(EventVO event) {
        EventEntity eventEntity = new EventEntity();
        beanMapper.map(event, eventEntity);
        eventDao.save(eventEntity);
        beanMapper.map(eventEntity, event);
        return event;
    }


    /**
     * 批量插入
     *
     * @param list 数据列表
     * @return 插入数据条数
     */
    @Transactional
    public void insertList(List<EventVO> list) {
        for (EventVO event : list) {
            insert(event);
        }
    }


    /**
     * 修改
     *
     * @param event 修改的数据
     * @return 修改的数据
     */
    @Transactional
    public EventVO update(EventVO event) {
        EventEntity eventEntity = null;
        if (StringUtils.isNotEmpty(event.getId())) {
            eventEntity = eventDao.findOne(Long.parseLong(event.getId()));
        }
        if (eventEntity == null) {
            eventEntity = new EventEntity();
        }
        beanMapper.map(event, eventEntity);
        eventDao.save(eventEntity);
        beanMapper.map(eventEntity, event);
        return event;
    }


    /**
     * 删除
     *
     * @param id 数据标识
     * @return 删除的数据条数
     */
    @Transactional
    public void delete(String id) {
        eventDao.deleteById(Long.parseLong(id));
    }


    /**
     * 查询所有数据
     *
     * @return 数据列表
     */
    public List<EventVO> getAll() {
        List<EventVO> list = Lists.newArrayList();
        List<EventEntity> entities = eventDao.findAllList();
        for (EventEntity eventEntity : entities) {
            EventVO eventVO = new EventVO();
            beanMapper.map(eventEntity, eventVO);
            list.add(eventVO);
        }
        return list;
    }


    /**
     * 通过条件查询数据列表
     *
     * @param event 查询条件
     * @return 数据列表
     */
    public List<EventVO> getList(EventVO event) {
        List<EventVO> list = Lists.newArrayList();
        DetachedCriteria dc = eventDao.createDetachedCriteria();
        dc.add(Restrictions.eq(EventEntity.DEL_FLAG, EventEntity.DEL_FLAG_NORMAL));

        List<EventEntity> entities = eventDao.find(dc);
        for (EventEntity eventEntity : entities) {
            EventVO eventVO = new EventVO();
            beanMapper.map(eventEntity, eventVO);
            list.add(eventVO);
        }
        return list;
    }


    /**
     * 通过id查询数据
     *
     * @param id 数据标识
     * @return 数据对象
     */
    public EventVO get(String id) {
        EventVO event = new EventVO();
        EventEntity eventEntity = eventDao.findOne(Long.parseLong(id));
        if (eventEntity == null) {
            eventEntity = new EventEntity();
        }
        beanMapper.map(eventEntity, event);
        return event;
    }


    /**
     * 根据条件分页查询
     *
     * @param page
     * @param event
     * @return
     */
    public Page<EventVO> findEventByPage(Page<EventVO> page, EventVO event) {
        Page<EventEntity> pageEntity = new Page<EventEntity>(page.getPageNo(), page.getPageSize());
        DetachedCriteria dc = eventDao.createDetachedCriteria();
        dc.add(Restrictions.eq(EventEntity.DEL_FLAG, EventEntity.DEL_FLAG_NORMAL));
        if (StringUtils.isNotEmpty(event.getFormal())) {
            dc.add(Restrictions.or(Restrictions.eq("formal", Integer.parseInt(event.getFormal())), Restrictions.eq("formal", 2)));
        }
        if (!StringUtils.isNotEmpty(page.getOrderBy())) {
            dc.addOrder(Order.asc("seq"));
        }
        pageEntity = eventDao.find(pageEntity, dc);
        beanMapper.map(pageEntity, page);
        List<EventVO> list = Lists.newArrayList();
        for (EventEntity eventEntity : pageEntity.getList()) {
            EventVO eventVO = new EventVO();
            beanMapper.map(eventEntity, eventVO);
            if (StringUtils.isNotBlank(event.getSemesterId())) {
                EventDetailEntity eventDetail = eventDetailDao.findEventDetail(eventEntity.getId(), Long.parseLong(event.getSemesterId()));
                if (eventDetail != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    eventVO.setStartTime(sdf.format(eventDetail.getStartTime()));
                    eventVO.setEndTime(sdf.format(eventDetail.getEndTime()));
                    if (eventDetail.getEndTime().before(new Date())) {
                        eventVO.setStatus("3");
                    } else {
                        eventVO.setStatus("" + eventDetail.getStatus());
                    }
                } else {
                    eventVO.setStatus("0");
                }
            }
            list.add(eventVO);
        }
        page.setList(list);
        return page;
    }


    /**
     * 开始事件的方法
     */
    @Transactional
    public void begin(EventVO eventVO, String semesterId) {
        try {
            // 先将事件查询出来
            boolean sendMessage = false;
            EventEntity eventEntity = eventDao.findOne(Long.parseLong(eventVO.getId()));
            SemesterEntity semesterEntity = semesterDao.findOne(Long.parseLong(semesterId));
            EventDetailEntity eventDetail = eventDetailDao.findEventDetail(eventEntity.getId(), Long.parseLong(semesterId));

            if (eventEntity.getFormal() != semesterEntity.getFormal() && eventEntity.getFormal() != 2) {
                return;
            }
            if (eventDetail == null) {
                eventDetail = new EventDetailEntity();
                eventDetail.setEvent(eventEntity);
                eventDetail.setSemester(semesterEntity);
                sendMessage = true;
            } else {
                if (eventDetail.getStatus() != 1 || eventDetail.getEndTime().before(new Date())) {
                    sendMessage = true;
                }
            }

            eventDetail.setStatus(1);
            eventDetail.setStartTime(new Date());
            DateTime dateTime = new DateTime();
            dateTime = dateTime.plusSeconds(eventEntity.getSeconds());
            eventDetail.setEndTime(dateTime.toDate());
            eventDetailDao.save(eventDetail);

            List<ParentEntity> parentEntities = semesterEntity.getParentEntities();
            List<EventCaseVO> messages = Lists.newArrayList();

            for (ParentEntity parentEntity : parentEntities) {

                DateTime start = new DateTime();
                DateTime end = start.plusDays(1);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                if (sendMessage) {
                    EventCaseEntity eventCaseEntity = new EventCaseEntity();
                    eventCaseEntity.setBegin(1);
                    eventCaseEntity.setEvent(eventEntity);
                    eventCaseEntity.setParent(parentEntity);
                    eventCaseEntity.setSemester(semesterEntity);
                    eventCaseEntity.setFlag("0");
                    eventCaseEntity.setUrl(eventEntity.getUrl());
                    int type = eventEntity.getType();
                    if (type != 9) {
                        eventCaseEntity = eventCaseDao.save(eventCaseEntity);
                    }
                    EventCaseVO eventCaseVO = new EventCaseVO();
                    beanMapper.map(eventCaseEntity, eventCaseVO);
                    messages.add(eventCaseVO);

                    //添加parentDailyScore数据
                    ParentDailyScoreEntity pdse = null;
                    DetachedCriteria dc1 = parentDailyScoreDao.createDetachedCriteria();
                    dc1.add(Restrictions.eq(ParentDailyScoreEntity.DEL_FLAG, ParentDailyScoreEntity.DEL_FLAG_NORMAL));
                    dc1.add(Restrictions.eq("parent.id", parentEntity.getId()));
                    dc1.add(Restrictions.eq("date", sdf.parse(sdf.format(start.toDate()))));
                    List<ParentDailyScoreEntity> list = parentDailyScoreDao.find(dc1);
                    if (list != null && list.size() > 0) pdse = list.get(0);
                    if (pdse == null) pdse = new ParentDailyScoreEntity();

                    //事件类型 0.录音 1.录像 2.拍照 3.计时 4.计数 5.评价 6.评分 7.作业 8.答案
                    if (type == 0) pdse.setTapeall(pdse.getTapeall() + 1);
                    if (type == 1) pdse.setVideotapeall(pdse.getVideotapeall() + 1);
                    if (type == 2) pdse.setPhotographall(pdse.getPhotographall() + 1);
                    if (type == 3) pdse.setTimeall(pdse.getTimeall() + 1);
                    if (type == 4) pdse.setCountall(pdse.getCountall() + 1);
                    if (type == 5) pdse.setEvaluateall(pdse.getEvaluateall() + 1);
                    if (type == 6) pdse.setScoreall(pdse.getScoreall() + 1);
                    if (type == 7) pdse.setHomeworkall(pdse.getHomeworkall() + 1);
                    if (type == 8) pdse.setAnswerall(pdse.getAnswerall() + 1);
                    pdse.setDate(new Date());
                    pdse.setKnowledge(pdse.getKnowledge() + eventEntity.getKnowledge());
                    pdse.setParent(parentEntity);
                    pdse.setSemester(semesterEntity);
                    parentDailyScoreDao.save(pdse);
                } else {
                    List<EventCaseEntity> list = eventCaseDao.findEventCase(eventEntity.getId(), parentEntity.getId(), semesterEntity.getId(), sdf.parse(sdf.format(start.toDate())), sdf.parse(sdf.format(end.toDate())));
                    for (EventCaseEntity eventCaseEntity : list) {
                        eventCaseEntity.setBegin(1);
                        eventCaseDao.save(eventCaseEntity);
                    }
                }

            }

            if (eventEntity.getType() < 9) {
                Thread thread = new Thread(() -> {
                    try {
                        for (EventCaseVO eventCaseVO : messages) {
                            WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
                            System.out.println("openID：" + eventCaseVO.getParent().getWeChatUser().getOpenId());
                            templateMessage.setToUser(eventCaseVO.getParent().getWeChatUser().getOpenId());
                            templateMessage.setTemplateId("bbFJynRv6IlfceKrPx-BlkxHlD7csJVXGNeZclEVyWA");
                            templateMessage.getData().add(new WxMpTemplateData("first", eventCaseVO.getEvent().getWxfirst()));
                            templateMessage.getData().add(new WxMpTemplateData("keyword1", eventCaseVO.getEvent().getWxkeyword1()));
                            templateMessage.getData().add(new WxMpTemplateData("keyword2", eventCaseVO.getEvent().getWxkeyword2()));
                            templateMessage.getData().add(new WxMpTemplateData("remark", eventCaseVO.getEvent().getWxremark()));
                            templateMessage.setUrl("http://ketang.fanrenqiji.com/message/getMessage?semesterId=" + semesterEntity.getId()
                                    + "&parentId=" + eventCaseVO.getParent().getId() + "&eventId=" + eventEntity.getId() + "&eventCaseId=" + eventCaseVO.getId());
                            try {
                                wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                            } catch (WxErrorException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                thread.start();
            } else {
                Thread thread = new Thread(() -> {
                    try {
                        for (EventCaseVO eventCaseVO : messages) {
                            try {
                                if(StringUtils.isNotBlank(eventCaseVO.getEvent().getWxtitle())){
                                    WxMpKefuMessage.WxArticle article1 = new WxMpKefuMessage.WxArticle();
                                    article1.setDescription(eventCaseVO.getEvent().getWxcontent());
                                    article1.setTitle(eventCaseVO.getEvent().getWxtitle());
                                    if("this".equals(eventCaseVO.getEvent().getWxurl())) {
                                        article1.setUrl("http://ketang.fanrenqiji.com/message/getMessage?semesterId=" + semesterEntity.getId()
                                                + "&parentId=" + eventCaseVO.getParent().getId() + "&eventId=" + eventEntity.getId() + "&eventCaseId=1");
                                    }else{
                                        article1.setUrl(eventCaseVO.getEvent().getWxurl());
                                    }
                                    article1.setPicUrl(eventCaseVO.getEvent().getWxpic());
                                    WxMpKefuMessage message = WxMpKefuMessage
                                            .NEWS()
                                            .toUser(eventCaseVO.getParent().getWeChatUser().getOpenId())
                                            .addArticle(article1)
                                            .build();
                                    try {
                                        wxService.getKefuService().sendKefuMessage(message);
                                    } catch (WxErrorException e) {
                                        e.printStackTrace();
                                    }
                                }else {
                                    WxMpKefuMessage message = new WxMpKefuMessage();
                                    message.setToUser(eventCaseVO.getParent().getWeChatUser().getOpenId());
                                    message.setMsgType(WxConsts.CUSTOM_MSG_TEXT);
                                    message.setContent(eventCaseVO.getEvent().getWxcontent());
                                    wxService.getKefuService().sendKefuMessage(message);
                                }
                            } catch (WxErrorException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                thread.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional
    public void end(EventVO eventVO, String semesterId) {
        EventEntity eventEntity = eventDao.findOne(Long.parseLong(eventVO.getId()));
        SemesterEntity semesterEntity = semesterDao.findOne(Long.parseLong(semesterId));

        EventDetailEntity eventDetail = eventDetailDao.findEventDetail(eventEntity.getId(), Long.parseLong(semesterId));

        if (eventDetail == null) {
            eventDetail = new EventDetailEntity();
            eventDetail.setEvent(eventEntity);
            eventDetail.setSemester(semesterEntity);
        }
        eventDetail.setStatus(3);
        eventDetail.setEndTime(new Date());
        eventDetailDao.save(eventDetail);

        try {
            eventDao.updateBySql("update tb_event_case set begin=3 where event_id=? and create_date>date_format(now(),'%Y-%m-%d')", eventVO.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    public void kaishishangke(String content, String time, String semesterId) {
        Calendar c = Calendar.getInstance();
        int i = c.get(Calendar.WEEK_OF_YEAR);//第几周
        // i 是当前的学期号 根据学期号来进行查询
        int year = c.get(Calendar.YEAR);
        String d;

        SemesterEntity semesterEntity = semesterDao.findOne(Long.parseLong(semesterId));

        for (int j = 0; j < 2; j++) {
            i++;
            d = year + "" + i;
            DetachedCriteria dc1 = semesterDao.createDetachedCriteria();
            dc1.add(Restrictions.eq("number", d));
            List<SemesterEntity> semesterEntities1 = semesterDao.find(dc1);
            if (semesterEntities1.isEmpty()) {
                SemesterEntity semesterEntity1 = new SemesterEntity();
                semesterEntity1.setNumber(d);
                semesterEntity1.setFormal(0);
                semesterEntity1.setEnroll(1);
                semesterDao.save(semesterEntity1);
            }
        }

        List<String> list = Lists.newArrayList();
        List<ParentEntity> parentEntities = semesterEntity.getParentEntities();
        for (ParentEntity parentEntity : parentEntities) {
            list.add(parentEntity.getWeChatUser().getOpenId());
        }
        Thread thread = new Thread(() -> {
            try {
                for (String openId : list) {
                    WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
                    templateMessage.setToUser(openId);
                    templateMessage.setTemplateId("ps_TyicVLhvRwH-NyT8a2CoXVrDYvvfT6n879Ew8K9A");
                    templateMessage.getData().add(new WxMpTemplateData("first", "Hi~您报名的直播马上开始啦！"));
                    templateMessage.getData().add(new WxMpTemplateData("keyword1", "奇迹课堂"));
                    templateMessage.getData().add(new WxMpTemplateData("keyword2", time));
                    templateMessage.getData().add(new WxMpTemplateData("remark", content));
                    try {
                        wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }

    @Transactional
    public void kechengyugao(String semesterId, String time) {
        SemesterEntity semesterEntity = semesterDao.findOne(Long.parseLong(semesterId));

        List<String> list = Lists.newArrayList();
        List<ParentEntity> parentEntities = semesterEntity.getParentEntities();
        for (ParentEntity parentEntity : parentEntities) {
            list.add(parentEntity.getWeChatUser().getOpenId());
        }
        Thread thread = new Thread(() -> {
            try {
                for (String openId : list) {
                    WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
                    templateMessage.setToUser(openId);
                    templateMessage.setTemplateId("ps_TyicVLhvRwH-NyT8a2CoXVrDYvvfT6n879Ew8K9A");
                    templateMessage.getData().add(new WxMpTemplateData("first", "下次课程上课时间预告"));
                    templateMessage.getData().add(new WxMpTemplateData("keyword1", "奇迹课堂"));
                    templateMessage.getData().add(new WxMpTemplateData("keyword2", time));
                    templateMessage.getData().add(new WxMpTemplateData("remark", "课程开始时会通知房间跟密码，不要错过哦"));
                    try {
                        wxService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }
}
